﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace EFCoreDemo
{
    public class MyHostService : BackgroundService
    {
        private readonly IServiceScopeFactory _serviceProvider;
        private readonly ILogger<MyHostService> _logger;
        public MyHostService(
            IServiceScopeFactory serviceProvider,
            ILogger<MyHostService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        protected async override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await TestAsync();
        }

        private async Task TestAsync()
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var userService = scope.ServiceProvider.GetService<IUserService>();
                var result = await userService.GetUserListAsync();
                _logger.LogInformation(System.Text.Json.JsonSerializer.Serialize(result, new System.Text.Json.JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = true }));
            }
        }
    }
}
